// toFixed 修复
function toFixed(num, s) {
  let times = Math.pow(10, s)
  let des = num * times + 0.5
  des = parseInt(des, 10) / times
  return des + ''
}
export default {
  data() {
    return {
      value: '',
      isEdit: false,
      location: {}, // 位置信息
      result: null,
      couponNum: 0, // 优惠券数量
      setMealNum: 0, // 套餐卡数量
      couponInfo: null, // 已选优惠券信息
      setMealInfo: null, // 已选套餐卡信息
      discountAmount: 0 ,// 优惠金额
      reason: '',// 备注信息
      oldCartList: [],
      invoicePopupShow: false, // 发票弹窗状态
      isinvoice: false,
      errorImg: 'https://files.yzsheng.com/client/index/carMaintenance/default.png'
    }
  },
  computed: {
    orderinfo() {
      return this.$store.state.maintenanceOrderInfo
    }
  },
  filters: {
    formatAmount(data) {
      if(data < 0) {
        return '0.00'
      } else {
        return toFixed(data, 2)
      }
    }
  },
  onLoad() {
    // #ifdef H5
    if (this.orderinfo) {
      let orderinfo = sessionStorage.maintenanceOrderInfo ? JSON.parse(sessionStorage.maintenanceOrderInfo) : []
      this.$store.commit('maintenanceOrderInfo', orderinfo)
    }
    // #endif
    this.oldCartList = JSON.parse(JSON.stringify(this.orderinfo.cartList))

    // 监听门店选择
    uni.$on('onSelectStore', data => {
      this.changeStore(data)
    })

    uni.showLoading({
      title: '加载中'
    })
    this.$commen.getLocation(data => {
      this.location = data
      this.getCouponAmount()
      this.clientAffirmCreateOrder()
    })

    // 监听选择优惠券
    uni.$on('changeCoupon', data => {
      if(data.is_Package) {
        this.setMealInfo = data.data
        this.discountAmount = data.discountTotalAmount
        this.couponInfo = null
      } else {
        this.couponInfo = data.data
        this.discountAmount = data.discountTotalAmount
        this.setMealInfo = null
      }

      // if(data.goodsList.length > 0) {
      //   this.oldCartList.map(item => {
      //     item.maintenanceGoodsLists.map(i => {
      //       data.goodsList.map(good => {
      //         if(i.maintenance_Type_Id === good.maintenance_Type_Id) {
      //           i.discountAmount = good.discountAmount
      //         }
      //       })
      //     })
      //   })
      // }

    })
  },
  methods: {
    // 点击导航
    onClickNavigation() {
      uni.openLocation({
        latitude: this.result.lat,
        longitude: this.result.lon
      })
    },
    // 维保订单_确认创建订单
    async clientAffirmCreateOrder() {
      // 请求参数组装
      let params = {
        lon: this.location.lon,
        lat: this.location.lat,
        configuration_id: this.orderinfo.myLoveCar.car_Id + '',
        goodslist: []
      }
      if(this.orderinfo.storeId) {
        params.store_id = this.orderinfo.storeId
      }
      this.orderinfo.cartList.map(item => {
        item.maintenanceGoodsLists.map(i => {
          params.goodslist.push({
            goods_id: i.id,
            goods_type_id: i.maintenance_Type_Id,
            count: i.amount
          })
        })
      })
      try {
        let res = await this.$api.maintenanceOrder.ClientAffirmCreateOrder(params)
        if (res.code === 200) {
          this.result = res.data
        }
        uni.hideLoading()
      } catch (e) {
        uni.hideLoading()
      }
    },
    // 提交订单
    async onSubmit() {
      let result = this.result
      let params = {
        store_id: result.store_id, // 店铺id
        love_car_id: this.orderinfo.myLoveCar.id, // 爱车id
        reason: this.reason, // 备注
        is_need_invoice: this.isinvoice, // 发票
        goodslist: [], // 商品列表
        servicelist: [], // 服务列表
        otherCoupons: null,
        CouponAllMoney: Number(this.discountAmount) > 0 ? -Number(this.discountAmount) : this.discountAmount
      }
      this.oldCartList.map(item => {
        item.maintenanceGoodsLists.map(i => {
          let goods = {
            count: i.amount,
            goods_id: i.id,
            remark: i.remark || '',
            discountAmount: i.discountAmount || 0
          }
          if(this.couponInfo) {
            goods.coupon_Id = this.couponInfo.coupon_Id
            goods.coupon_Details_Id = this.couponInfo.coupon_Details_Id
          }
          if(this.setMealInfo) {
            // goods.coupon_Id = this.setMealInfo.id
            this.setMealInfo.goods.map(s => {
              if(i.id === s.goods_Service_Type_Id) {
                goods.coupon_Id = s.coupon_Id
                goods.coupon_Details_Id = s.coupon_Details_Id
                goods.discountAmount = Number(s.discountAmount) > 0 ? -Number(s.discountAmount) : s.discountAmount
              }
            })
          }
          params.goodslist.push(goods)
        })
      })
      result.serviceProjectslist.map(item => {
        let service = item
        if(this.couponInfo) {
          // service.coupon_Details_Id = this.couponInfo.cid
          service.coupon_Id = this.couponInfo.coupon_Id
          service.coupon_Details_Id = this.couponInfo.coupon_Details_Id
        }
        if(this.setMealInfo) {
          // service.coupon_Id = this.setMealInfo.id
          this.setMealInfo.service.map(i => {
            if(item.serviceId === i.goods_Service_Type_Id) {
              service.coupon_Id = i.coupon_Id
              service.coupon_Details_Id = i.coupon_Details_Id
              service.discountAmount = Number(i.discountAmount) > 0 ? -Number(i.discountAmount) : i.discountAmount
            }
          })
        }
        params.servicelist.push(service)
      })

      if(this.setMealInfo && this.setMealInfo.deduction) {
        params.otherCoupons = this.setMealInfo.deduction
        params.otherCoupons.discountAmount = Number(params.otherCoupons.discountAmount) > 0 ? -Number(params.otherCoupons.discountAmount) : params.otherCoupons.discountAmount
      }
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      try{
        let res = await this.$api.maintenanceOrder.ClientCreateOrder(params)
        uni.hideLoading()
        if(res.code === 200) {
          if(res.data.isPay){
            let price = parseFloat(Number(this.result.total_money) - this.discountAmount).toFixed(2)
            price = Number(price) < 0 ? '0.00' : price
            uni.redirectTo({
              url: `/pages_commodity/payment/payment?orderNo=${res.data.orderid}&type=maintenanceorder&price=${price}`
            })
          } else {
            uni.redirectTo({
              url: `/pages_commodity/paySuccessful/paySuccessful?orderId=${res.data.orderid}`
            })
          }
        } else {
          uni.showToast({
            icon: 'none',
            title: res.msg
          })
        }
      }catch(e){
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: e || '请求错误'
        })
      }
    },
    // 跳转门店
    onChangeStore() {
      uni.navigateTo({
        url: '/pages_store/carMaintenanceStore/list/list?type=selectStore'
      })
    },
    // 选择门店修改信息
    changeStore(data) {
      this.result.store_address = data.address
      this.result.store_id = data.id
      this.result.store_name = data.store_name
      this.result.distance = data.distance
      this.result.lat = data.lat
      this.result.lon = data.lon
    },
    // 获取可用优惠券数量
    getCouponAmount() {
      let userinfo = uni.getStorageSync('Ztc_C_USER_INFO')
      if(userinfo) {
        let coupon = this.$api.user.GetCouponList({
          coupon_class: 2,
          pageIndex: 1,
          pageSize: 1,
          mobile: userinfo.mobile
        })
        let coupon1 = this.$api.user.GetCouponList({
          coupon_class: 4,
          pageIndex: 1,
          pageSize: 1,
          mobile: userinfo.mobile
        })
        Promise.all([coupon, coupon1]).then(data => {
          this.couponNum = data[0].data.total
          this.setMealNum = data[1].data.total
        })
      }
    },
    // 点击选择优惠券
    onClickCoupon(num, type) {
      let userinfo = uni.getStorageSync('Ztc_C_USER_INFO') || null
      if(num <= 0 || !userinfo) return false
      let data = {
        goodsList: this.orderinfo.cartList,
        serviceFeeList: this.result.serviceProjectslist,
        discountAmount: this.discountAmount,
        couponInfo: this.couponInfo ? this.couponInfo.cid : null,
        setMealInfo: this.setMealInfo ? this.setMealInfo.id : null
      }
      this.$store.commit('maintenanceOrder', data)
      // #ifdef H5
      sessionStorage.maintenanceOrder = JSON.stringify(data)
      // #endif
      uni.navigateTo({
        url: `/pages_userModule/myCoupon/choose?mobile=${userinfo.mobile}&status=${type}&from=order`
      })
    },
    // 点击选择发票
    onChangeInvoice() {
      this.invoicePopupShow = true
    },
    selectedInvoice(data) {
      this.isinvoice = data
      this.invoicePopupShow = false
    },
    // 清除优惠券
    onClearCoupon(type) {
      this[type] = null
    }
  },
  onUnload() {
    uni.$off('onSelectStore')
    uni.$off('changeCoupon')
    this.$store.commit('maintenanceOrder', null)
    // #ifdef H5
    delete sessionStorage.maintenanceOrder
    // #endif
  }
}
